import axios from 'axios'

import getHttpStatusText from '@/util/getHttpStatusText'

axios.interceptors.request.use(cfg => {

  return cfg

}, err => [err.toString()])

axios.interceptors.response.use(res => {
  if (res.status !== 200) {
    return [`连接失败 code:${ res.status }`]
  }

  const { code, message, data } = res.data

  if (code.toString() !== '0') {

    if (code.toString() === '-2') {
      return ['登录认证信息失效']
    }

    return [message || '请求失败']
  }

  return [null, res.data]
}, err => {
  const { error, config, code, request, response } = err

  if (!response) {
    return ['未连接到服务器']
  }

  // 还是需要返回错误原信息,因为接口需要传递发送信息与接口的信息
  if (response.status) {
    return [getHttpStatusText(response.status), err]
  }

  return ['连接失败', err]
})


export default axios